package team.gl.nio.svr;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;

import java.util.Vector;

import com.richman.controller.NegativeRatioClient;

import team.gl.nio.cmn.Bag;
import team.gl.nio.cmn.NewBag;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        //System.out.println("server channelRead..");
        NewBag us = (NewBag) msg;
        if(us.getReq().equals("bdvalues")){
        	
        	if(NegativeRatioClient.mainWnd != null) {
            	NewBag bag = new NewBag("bdvalues");
            	bag.setBdvalues(NegativeRatioClient.mainWnd.getBetDvalues());
            	ctx.channel().writeAndFlush(bag);
        	}
        	
        	
        }
        if(us.getReq().equals("betAdyDatas")) {
        	if(NegativeRatioClient.mainWnd != null) {
            	NewBag bag = new NewBag("betAdyDatas");
            	bag.setBetAdyDatas(NegativeRatioClient.mainWnd.getBetAdyDatas());
            	ctx.channel().writeAndFlush(bag);
        	}
        }
        
    
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //System.out.println("server channelReadComplete..");
        ctx.flush();//ˢ�º�Ž���ݷ�����SocketChannel
    }
    

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        //System.out.println("server exceptionCaught.." + cause.getMessage());
        ctx.close();
    }
    
    
    
    
    // 心跳丢失计数器
    private int counter;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //System.out.println("--- Client is active ---");
    	

    	
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
       
    	String uuid = ctx.channel().id().asLongText();
    	
    	
    }



    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            // 空闲6s之后触发 (心跳包丢失)
            if (counter >= 3) {
                // 连续丢失3个心跳包 (断开连接)
                ctx.channel().close().sync();
                System.out.println("已与Client断开连接");
            } else {
                counter++;
                System.out.println("丢失了第 " + counter + " 个心跳包");
            }
        }
    }





}
